// utils/huawei-ocr-simple.js
// 简化的华为云OCR测试工具 - 尝试不同端点

const cryptoHelper = require('./crypto-helper.js')
const tokenManager = require('./token-manager.js')

class HuaweiOCRSimple {
  constructor() {
    this.config = {
      accessKeyId: 'M83S8VCVHYI3FJ9NJXMM',
      secretAccessKey: 'biUgKaKs18aAzQY1aH3JykGh9RNA3rIl0HcF38ky',
      region: 'cn-north-4',
      projectId: '05bfa947f88025502f62c00ea658fd4f'
    }
  }

  // 获取华为云认证Token（直接调用，用于调试）
  async getAuthToken() {
    try {
      const tokenUrl = 'https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens'
      
      const tokenRequest = {
        auth: {
          identity: {
            methods: ['password'],
            password: {
              user: {
                name: 'ilieyun',
                password: 'Lieyun@2090',
                domain: {
                  name: 'ilieyun'
                }
              }
            }
          },
          scope: {
            project: {
              name: 'cn-north-4'
            }
          }
        }
      }

      console.log('简化测试 - 获取Token请求:', tokenRequest)

      const response = await wx.request({
        url: tokenUrl,
        method: 'POST',
        data: tokenRequest,
        header: {
          'Content-Type': 'application/json'
        },
        timeout: 10000
      })

      console.log('简化测试 - Token响应状态码:', response.statusCode)
      console.log('简化测试 - Token响应头:', response.header)
      console.log('简化测试 - Token响应数据:', response.data)

      // 检查响应状态码，微信小程序可能返回undefined
      const statusCode = response.statusCode || response.status || 0
      console.log('简化测试 - 实际状态码:', statusCode)

      // 详细检查响应头
      if (response.header) {
        console.log('简化测试 - 响应头键名列表:', Object.keys(response.header))
        console.log('简化测试 - 查找X-Subject-Token...')
        
        // 尝试多种可能的键名
        const possibleKeys = [
          'X-Subject-Token',
          'x-subject-token',
          'X-SUBJECT-TOKEN',
          'x_subject_token'
        ]
        
        for (const key of possibleKeys) {
          if (response.header[key]) {
            console.log(`简化测试 - 找到Token，键名: ${key}`)
            const token = response.header[key]
            console.log('简化测试 - 获取到Token:', token.substring(0, 20) + '...')
            return token
          }
        }
        
        // 如果没有找到，打印所有响应头内容
        console.log('简化测试 - 所有响应头内容:')
        Object.keys(response.header).forEach(key => {
          console.log(`${key}: ${response.header[key]}`)
        })
      }
      
      // 如果没有找到Token
      if (statusCode === 201 || statusCode === 200) {
        // 状态码正确但没有Token，可能是响应头问题
        console.log('简化测试 - 状态码正确但未找到Token')
        throw new Error('Token获取成功但响应头中未找到X-Subject-Token')
      } else {
        throw new Error(`获取Token失败: ${statusCode}`)
      }
    } catch (error) {
      console.error('简化测试 - 获取Token异常:', error)
      throw error
    }
  }

  // 简化的OCR测试 - 尝试不同端点
  async testSimpleOCR() {
    console.log('=== 简化华为云OCR测试 (多端点) ===')
    
    try {
      // 测试1: 简单的GET请求测试连接
      await this.testBasicConnection()
      
      // 测试2: 尝试不同的API端点
      await this.testMultipleEndpoints()
      
      console.log('✅ 简化测试完成')
      return true
    } catch (error) {
      console.log('❌ 简化测试失败:', error.message)
      throw error
    }
  }

  // 测试基本连接
  async testBasicConnection() {
    console.log('测试基本网络连接...')
    
    const testUrls = [
      'https://www.baidu.com',
      'https://www.qq.com',
      'https://ocr.cn-north-4.myhuaweicloud.com'
    ]
    
    for (const url of testUrls) {
      try {
        const response = await wx.request({
          url: url,
          method: 'GET',
          timeout: 5000
        })
        
        console.log(`✅ ${url} 连接正常 (${response.statusCode})`)
      } catch (error) {
        console.log(`❌ ${url} 连接失败:`, error.message)
      }
    }
  }

  // 测试多个API端点
  async testMultipleEndpoints() {
    console.log('测试多个API端点...')
    
    // 获取Token
    const authToken = await this.getAuthToken()
    
    // 不同的API端点
    const endpoints = [
      'https://ocr.cn-north-4.myhuaweicloud.com/v2/05bfa947f88025502f62c00ea658fd4f/ocr/general-text',
      'https://ocr.cn-north-4.myhuaweicloud.com/v1.0/ocr/general-text',
      'https://ocr.cn-north-4.myhuaweicloud.com/v2.0/ocr/general-text',
      'https://ocr.cn-north-4.myhuaweicloud.com/ocr/general-text',
      'https://ocr.cn-north-4.myhuaweicloud.com/v1/ocr/general-text'
    ]
    
    for (let i = 0; i < endpoints.length; i++) {
      const apiUrl = endpoints[i]
      console.log(`\n测试端点 ${i + 1}: ${apiUrl}`)
      
      try {
        const headers = {
          'Content-Type': 'application/json',
          'X-Auth-Token': authToken
        }

        const requestBody = {
          image: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
          url: null,
          detect_direction: true,
          quick_mode: false,
          paragraph: false,
          probability: true
        }

        console.log('请求头:', headers)
        console.log('请求体大小:', JSON.stringify(requestBody).length, '字节')

        const response = await wx.request({
          url: apiUrl,
          method: 'POST',
          data: requestBody,
          header: headers,
          timeout: 10000
        })

        console.log('响应状态码:', response.statusCode)
        console.log('响应头:', response.header)
        console.log('响应数据:', response.data)

        if (response.statusCode === 200) {
          console.log(`✅ 端点 ${apiUrl} 测试成功`)
          return apiUrl
        } else {
          console.log(`⚠️ 端点 ${apiUrl} 返回状态码: ${response.statusCode}`)
        }
      } catch (error) {
        console.log(`❌ 端点 ${apiUrl} 测试失败:`, error.message)
      }
    }
    
    throw new Error('所有端点测试失败')
  }

  // 运行完整测试
  async runFullTest() {
    console.log('=== 华为云OCR完整测试 (多端点) ===')
    
    try {
      await this.testBasicConnection()
      await this.testMultipleEndpoints()
      
      console.log('✅ 完整测试通过')
      return true
    } catch (error) {
      console.log('❌ 完整测试失败:', error.message)
      throw error
    }
  }
}

module.exports = new HuaweiOCRSimple()
